package com.yc.javaee.servlet.d0615;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 *  1.实现登录  ( 表单方式提交)
 *      1. 验证用户信息
 *      2. 将用户名保存到会话中
 *      3. 提示成功!
 *  2.登录成功之后, 再次访问 index.html 那么在index.html
 *      显示登录的用户名 ( ajax 方式)
 */

@WebServlet(name = "LoginServlet", value = "/login.s")
public class LoginServlet extends HttpServlet {

    List<String> users = Arrays.asList("yc","武松","林冲","曹盖","吴用");

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("name");
        String password = request.getParameter("pwd");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        if(users.contains(username) && "123".equals(password)){
            HttpSession session = request.getSession();
            // 将当前登录的用户名保存到会话中
            session.setAttribute("loginedUser", username);
            out.append("<div style='text-align:center'>").append("登录成功<br>")
                    .append("<a href='0615/index.html'>回到首页</a></div>");
        } else {
            out.append("<div style='text-align:center'>").append("登录失败<br>")
                    .append("<a href='0615/用户登录.html'>回到登录页</a></div>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
